import { OnInit, Component, Output, EventEmitter, ViewChild, Input } from '@angular/core';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { NzMessageService } from 'ng-zorro-antd';
import { StudentCourseService } from 'src/app/project/service/icm/icm-student-academic/student-course/student-course.service';
import { FormBuilder, NgForm, FormGroup, Validators } from '@angular/forms';
import { StudentCourseDTO } from 'src/app/project/model/icm/icm-student-academic/student-course/student-course.dto';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { CourseTypeDTO } from 'src/app/project/model/icm/icm-base/course-type/course-type.dto';
import { CourseDTO } from 'src/app/project/model/icm/icm-base/course/course.dto';
import { TeacherDTO } from 'src/app/project/model/icm/icm-system-user/teacher/teacher.dto';
import { CourseTeacherDTO } from 'src/app/project/model/icm/icm-start-course/start-course/course-teacher.dto';
import { STColumn } from '@delon/abc';
import { FormUtil } from '@shared/utils/form-util';
import { StudentDTO } from 'src/app/project/model/icm/icm-system-user/student/student.dto';
import { CourseTeacherService } from 'src/app/project/service/icm/icm-start-course/start-course/course-teacher.service';
import { format } from 'date-fns';

@Component({
  selector: 'app-student-course-detail',
  templateUrl: './student-course-detail.component.html',
  styles: [],
})
export class StudentCourseDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private studentCourseService: StudentCourseService,
    private fb: FormBuilder,
    private courseTeacherService: CourseTeacherService,
  ) {
    this.validateForm = this.fb.group({
      year: ['', [Validators.required]],
      termType: ['', [Validators.required]],
      credit: [{ value: '', disabled: true }, [Validators.required]],
      courseType: [{ value: '', disabled: true }, [Validators.required]],
      teacherName: [{ value: '', disabled: true }],
      degreeType: [{ value: '', disabled: true }],
      studyStatus: ['', [Validators.required]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<StudentCourseDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'year,desc',
  };

  @Input()
  student: StudentDTO;

  /**
   * 课程类型信息
   */
  courseType: CourseTypeDTO = {
    id: null,
    code: null,
    name: null,
    courseBaseType: null,
    showOrder: 0,
  };

  /**
   * 课程信息
   */
  course: CourseDTO = {
    id: null,
    code: '',
    name: null,
    courseType: this.courseType,
    evaluationMode: null,
    credit: null,
    showOrder: 0,
  };

  /**
   * 教师信息
   */
  teacher: TeacherDTO = {
    id: null,
    code: '',
    name: '',
    gender: '',
    degreeType: '',
    birthDate: '',
    joinTime: '',
    isSenator: false,
    isInstructor: false,
  };

  /**
   * 课程开课信息
   */
  courseTeacher: CourseTeacherDTO = {
    id: null,
    year: '',
    termType: '',
    evaluationMode: '',
    isOpen: true,
    courseName: '',
    course: this.course,
    teacher: this.teacher,
    nextYear: null,
  };

  /**
   * 学生选课信息
   */
  studentCourse: StudentCourseDTO = {
    id: null,
    year: '',
    nextYear: null,
    termType: '',
    studyStatus: '',
    courseTeacher: this.courseTeacher,
    student: this.student,
  };

  /**
   * 课程开课信息下拉
   */
  courseTeacherList: Array<CourseTeacherDTO>;

  /**
   * 表格的列定义
   */
  courseTeacherColumns: STColumn[] = [
    {
      title: '序号',
      type: 'no',
      width: '2%',
      className: 'text-center',
    },
    {
      title: '学年',
      index: 'year',
      width: '4%',
      className: 'text-center',
      format(item) {
        return `${item.year} - ${Number.parseInt(item.year, 10) + 1} 学年`;
      },
    },
    {
      title: '学期',
      index: 'termType',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.termType === 'LAST_TERM' ? '第一学期' : '第二学期';
      },
    },
    {
      title: '课程编号',
      index: 'course.code',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '课程名称',
      index: 'course.name',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '教师编号',
      index: 'teacher.code',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '授课教师',
      index: 'teacher.name',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '是否开课',
      index: 'isOpen',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.isOpen ? '是' : '否';
      },
    },
  ];

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    this.courseTeacher.courseName = null;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 获取选中的课程开课信息
   * @param $event 选中的课程开课信息
   */
  getCourseTeacherChange($event) {
    this.studentCourse.courseTeacher = $event;
  }

  /**
   * 修改或新增教师信息
   * @param isPreView 是否预览
   * @param item 教师信息
   */
  edit(isPreView: boolean, item: StudentCourseDTO) {
    this.isPreView = isPreView;

    this.studentCourse = this.initStudentCourse(item);
    this.isVisible = true;

    // 获取所有课程开课信息
    this.courseTeacherService.findOnePage(this.queryOptions, null, null, null, null, true).subscribe(data => {
      this.courseTeacherList = data.data;
    });
  }

  /**
   * 初始化课程
   */
  initStudentCourse(item: StudentCourseDTO): StudentCourseDTO {
    return {
      id: item ? item.id : null,
      year: item ? item.year : null,
      nextYear: item ? Number.parseInt(item.year, 10) + 1 : null,
      termType: item ? item.termType : null,
      studyStatus: item ? item.studyStatus : 'SELECKED_CLASS',
      courseTeacher: item ? item.courseTeacher : this.courseTeacher,
      student: item ? item.student : this.student,
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.studentCourse.year === null) {
      this.msg.error('学年必选');
      return false;
    } else {
      this.studentCourse.year = format(this.studentCourse.year, 'YYYY');
    }
    if (this.studentCourse.termType === null) {
      this.msg.error('学期必选');
      return false;
    }
    if (this.studentCourse.studyStatus === null) {
      this.msg.error('修读状态必选');
      return false;
    }
    if (!this.studentCourse.courseTeacher.id) {
      this.msg.error('课程必选');
      return false;
    }

    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.studentCourse.id) {
      // id为空，为新建
      this.studentCourseService.create(this.studentCourse).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.studentCourseService.complete(this.studentCourse.id, this.studentCourse).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: StudentCourseDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {}
}
